import React, { PureComponent as Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import MethodEditForm from './MethodEditForm.js';
import {
  updateCurMethodData,
  changeMethodData,
  // fetchMethodListMenu,
  fetchMethodData
} from '../../../../reducer/modules/dubboMethod.js';
import { message } from 'antd';
import './Edit.scss';
import { withRouter } from 'react-router-dom';

@connect(
  state => {
    return {
      curMethod: state.dubboMethod.curMethod,
      curProject: state.dubboProject.curProject
    };
  },
  {
    updateCurMethodData,
    changeMethodData,
    fetchMethodData
  }
)
class InterfaceEdit extends Component {
  static propTypes = {
    curMethod: PropTypes.object,
    currProject: PropTypes.object,
    updateCurMethodData: PropTypes.func,
    changeMethodData: PropTypes.func,
    fetchMethodData: PropTypes.func,
    match: PropTypes.object,
    switchToView: PropTypes.func
  };

  constructor(props) {
    super(props);
    this.state = {
      curMethod: {},
      status: 0,
      visible: false,
      errorMsg: ''
    };
  }

  onSubmit = async params => {
    params.id = this.props.match.params.actionId;
    let result = await this.props.changeMethodData(params);
    if (result.payload.data.errcode === 0) {
      message.success('保存成功');
    } else {
      message.error(result.payload.data.errmsg);
    }
  };

  componentWillUnmount() {
    try {
      if (this.state.status === 1) {
        this.WebSocket.close();
      }
    } catch (e) {
      return null;
    }
  }

  componentDidMount() {
    let domain = location.hostname + (location.port !== '' ? ':' + location.port : '');
    let s,
      initData = false;
    //因后端 node 仅支持 ws， 暂不支持 wss
    let wsProtocol = location.protocol === 'https:' ? 'wss' : 'ws';

    setTimeout(() => {
      if (initData === false) {
        this.setState({
          curMethod: this.props.curMethod,
          status: 1
        });
        initData = true;
      }
    }, 3000);

    try {
      s = new WebSocket(
        wsProtocol + 
        '://' +
        domain +
        '/api/dubbomethod/solve_conflict?id=' +
        this.props.match.params.actionId
        );
      s.onopen = () => {
        this.WebSocket = s;
      };
      s.onmessage = e => {
        initData = true;
        let result = JSON.parse(e.data);
        if (result.param_err){
          this.setState({
            status: 4,
            errorMsg: '' + result.data.message
          })
        } else {
          if (result.errno === 0) {
            this.setState({
              curMethod: result.data,
              status: 1
            });
          } else {
            this.setState({
              curMethod: result.data,
              // 不做并发控制
              // status: 2
              status: 1
            });
          }
        }
      };

      s.onerror = () => {
        this.setState({
          curMethod: this.props.curMethod,
          status: 1
        });
        console.warn('websocket 连接失败，将导致多人编辑同一个接口冲突。');
      };
    } catch (e) {
      this.setState({
        curMethod: this.props.curMethod,
        status: 1
      });
      console.error('websocket 连接失败，将导致多人编辑同一个接口冲突。');
    }
  }

  onTagClick = () => {
    this.setState({
      visible: true
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false
    });
  };

  tagSubmit = tagRef => {
    this.tag = tagRef;
  };

  render() {
    return (
      <div className="interface-edit">
        {this.state.status === 1 ? (
          <MethodEditForm
            onSubmit={this.onSubmit}
            curdata={this.state.curMethod}
          />
        ) : null}
        {this.state.status === 2 ? (
          <div style={{ textAlign: 'center', fontSize: '14px', paddingTop: '10px' }}>
            <span>正在编辑该接口，请稍后再试...</span>
          </div>
        ) : null}
        {this.state.status === 0 && '正在加载，请耐心等待...'}
        {this.state.status === 4 && 'ERROR!' + this.state.errorMsg}
      </div>
    );
  }
}

export default withRouter(InterfaceEdit);
